import argparse, os, logging, sys

from engine.project._json import JSONBasedProjectLoader as ProjectLoader

parser = argparse.ArgumentParser()
parser.add_argument('file_path', nargs='?')
parser.add_argument('-a', '--archive', action='store_true', help='Specify whether the project is in a compressed archive e.g. a Zip file')
parser.add_argument('-r', '--render', action='store_true', help='Render the project and exit')
parser.add_argument('-l', '--log', help='Set the logging level', default='INFO')
args = parser.parse_args()

numeric_level = getattr(logging, args.log.upper(), None)
if not isinstance(numeric_level, int):
    raise ValueError('Invalid log level: %s' % args.log)

logging.basicConfig(
    level=numeric_level,
    datefmt='%m/%d/%Y %I:%M:%S',
    format='[%(asctime)s] %(name)s %(levelname)s: %(message)s'
)

logger = logging.getLogger(__name__)

if __name__ == '__main__':
    if args.archive:
        logger.critical('Archived project handling not implemented')
        sys.exit(1)

    if args.render:
        if args.file_path:
            if os.path.exists(args.file_path):
                if os.path.isdir(args.file_path):
                    loader = ProjectLoader(args.file_path)
                    engine = loader.get_engine()
                    os.makedirs('output', exist_ok=True)
                    engine.render_and_save_animation('output')
                elif os.path.isfile(args.file_path):
                    pass # TODO Check if path is compressed archive and if so, extract it to a temporary directory and start
                else:
                    logger.critical('Can\'t render project because the project path is neither a file or directory')
                    sys.exit(1)
            else:
                logger.critical('Can\'t render project because the project path doesn\'t exist')
                sys.exit(1)
        else:
            logger.critical('Can\'t render project because a project path hasn\'t been set')
            sys.exit(1)
    else:
        import gui
        gui.main(args)
